package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.CommonEntity;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
public class DishController {
    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private RedisTemplate redisTemplate;

    @PostMapping
    public R saveDish(@RequestBody DishDto dishDto) {
        dishService.saveWithFlavor(dishDto);
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    @GetMapping("/page")
    public R list(Integer page, Integer pageSize, String name) {
        Page<Dish> pageinfo = new Page<>(page, pageSize);

        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.like(StrUtil.isNotEmpty(name), Dish::getName, name);
        qw.orderByDesc(CommonEntity::getUpdateTime);
        dishService.page(pageinfo, qw);

        long total = pageinfo.getTotal();
        List<Dish> records = pageinfo.getRecords();
        ArrayList<DishDto> dishDtos = new ArrayList<>();
        for (Dish dish : records) {
            //获取菜品分类id
            Long categoryId = dish.getCategoryId();
            Category category = categoryService.getById(categoryId);
            //获取到了当前分类的名称
            String categoryName = category.getName();
            // 新建一个DishDto 将分类名称set进入
            DishDto dishDto = new DishDto();
            dishDto.setCategoryName(categoryName);
            // 还需要将Dish dish 数据放入到 DishDto dishDto 里面
            BeanUtils.copyProperties(dish, dishDto);
            dishDtos.add(dishDto);
        }
        Map data = new HashMap();
        data.put("total", total);
        data.put("records", dishDtos);
        return R.success(data);
    }

    @GetMapping("/{id}")
    public R getone(@PathVariable Long id) {
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    @PutMapping
    public R updateDish(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
        return R.success("修改菜品成功");
    }

    @DeleteMapping
    public R delete(@RequestParam List<Long> ids) {
        dishService.delete(ids);
        return R.success("删除成功");
    }

    @PostMapping("/status/{status}")
    public R updateStatus(@PathVariable Integer status, @RequestParam List<Long> ids) {
        for (Long id : ids) {
            Dish dish = dishService.getById(id);
            dish.setStatus(status);
            dishService.updateById(dish);
            String key="dish_"+dish.getCategoryId()+"_1";
            redisTemplate.delete(key);
        }
        return R.success("操作成功");
    }

    @GetMapping("/list")
    public R list(Long categoryId, Integer status) {
        String key = "dish_" + categoryId + "_" + status;
        List<DishDto> dishDtos;
        dishDtos = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if (dishDtos != null) {
            return R.success(dishDtos);
        }
        LambdaQueryWrapper<Dish> qw = new LambdaQueryWrapper<>();
        qw.eq(Dish::getCategoryId, categoryId).eq(Dish::getStatus, status);
        List<Dish> list = dishService.list(qw);

        dishDtos = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtil.copyProperties(item, dishDto);
            LambdaUpdateWrapper<DishFlavor> qw1 = new LambdaUpdateWrapper<>();
            qw1.eq(DishFlavor::getDishId, item.getId());
            List<DishFlavor> flavors = dishFlavorService.list(qw1);
            dishDto.setFlavors(flavors);
            return dishDto;
        }).collect(Collectors.toList());

        redisTemplate.opsForValue().set(key, dishDtos, 10, TimeUnit.MINUTES);

        return R.success(dishDtos);
    }
}
